import React, {
    Component,
} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Image,
    Alert,
    FlatList,
    TextInput,
    Linking,
    ScrollView,
    Switch,
    DeviceEventEmitter,
} from 'react-native';
import AndroidModule from 'src/utils/AndroidConnent'
import Loading from "../../../utils/Loading";
import HttpUtils from '../../../utils/HttpUtils';
import HttpUrls from '../../../utils/HttpUrls';
import Header from "../../../components/header";
import PublishCarArrow from '../publishCar/components/PublishCarArrow';
import PublishCarTextInput from '../publishCar/components/PublishCarTextInput';
import Constant from '../../../utils/Constant'//全局变量
import { ToastToUser } from '../../../utils/CustomToast';
import Picker from 'react-native-picker'
import DatePickerPart from '../../../components/Tool/DatePickerPart'
import { getImgUrl } from '../../../utils/ComFunction'
import { conditionObjWithType } from '../../../utils/Conditions'
import PublishCarSwitch from '../publishCar/components/PublishCarSwitch'


let navigation

export default class CarPriceSettingPage extends Component {
    constructor(props) {
        super(props);
        let carId = this.props.route && this.props.route.params && this.props.route.params.carId ? this.props.route.params.carId : ''
        this.state = {
            carId: carId,
            data: {},
            isFranchisee: Constant.userInfo.isFranchisee,//是否加盟商 0：否，1：是
            purchasePrice: '', //采购价
            markedPrice: '', //展厅价
            listPrice: '', //挂牌价
            wholesalePrice: '', //批发价
            joinQuotationCenter: false, //上架到报价中心
            joinUnion: false, //上架到严选车源
            isJoin: false,

        }
    }

    componentDidMount() {
        this.getOwnCarDetails()
    }

    getOwnCarDetails() {
        let param = {
            carId: this.state.carId
        }
        if (this.Loading) {
            this.Loading.show();
        }
        HttpUtils.getRequest(HttpUrls.getOwnCarDetails, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                let data = result.data
                let isJoin = (this.state.isFranchisee && data.joinQuotationCenter) || (!this.state.isFranchisee && data.joinUnion)

                this.setState({
                    isJoin,
                    data,
                    purchasePrice: data.purchasePrice ? (data.purchasePrice / 10000).toFixed(2) + '' : '',
                    markedPrice: data.markedPrice ? (data.markedPrice / 10000).toFixed(2) + '' : '',
                    listPrice: data.listPrice ? (data.listPrice / 10000).toFixed(2) + '' : '',
                    wholesalePrice: data.wholesalePrice ? (data.wholesalePrice / 10000).toFixed(2) + '' : '',
                    joinQuotationCenter: data.joinQuotationCenter ? true : false,
                    joinUnion: data.joinUnion ? true : false
                })
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'设置价格'}></Header>
                <ScrollView
                    style={{ flex: 1 }}
                >
                    <View style={styles.contentContainer}>

                        <View style={styles.carInfoBox}>
                            <View style={styles.carBox}>
                                <Image style={styles.carImg} source={{ uri: this.state.data && this.state.data.carPics ? getImgUrl(this.state.data.carPics[0].picUrl) : '' }} />
                                <View style={styles.carRightBox}>
                                    <Text style={styles.brandText} numberOfLines={1}>{this.state.data && this.state.data.seriesName ? this.state.data.seriesName + ' ' + this.state.data.speciesName : ''}</Text>
                                    <Text style={styles.dateText}>{(this.state.data.registerDate && this.state.data.registerDate.length >= 2 ? this.state.data.registerDate.split('-')[0] + '-' + this.state.data.registerDate.split('-')[1] : '') + (this.state.data.mileage ? (' | ' + (this.state.data.mileage / 10000).toFixed(2) + '万公里') : '')}</Text>
                                    <Text style={styles.priceText}>{this.state.data && this.state.data.guidePrice ? '指导价：' + (this.state.data.guidePrice / 10000).toFixed(2) + '万元' : ''}</Text>
                                </View>
                            </View>
                            <View style={styles.markBox}>
                                {/* 库存状态 */}
                                {
                                    this.state.data.storeStatus ?
                                        <View style={styles.labelItemBox}>
                                            <Text style={styles.labelText}>{conditionObjWithType('storeStatus')[this.state.data.storeStatus]}</Text>
                                        </View>
                                        :
                                        null
                                }
                                {/* 库龄 */}
                                {
                                    this.state.data.purchaseDate ?
                                        <View style={styles.labelItemBox}>
                                            <Text style={styles.labelText}>{'库存' + this.getDaysBetweenDates(this.state.data.purchaseDate) + '天'}</Text>
                                        </View>
                                        :
                                        null
                                }
                                {/* 收购性质，在全款的时候隐藏 */}
                                {
                                    this.state.data.purchaseType && this.state.data.purchaseType != 1 ?
                                        <View style={styles.labelItemBox}>
                                            <Text style={styles.labelText}>{conditionObjWithType('purchaseType')[this.state.data.purchaseType]}</Text>
                                        </View>
                                        :
                                        null
                                }
                                {/* 已上架/未上架 */}
                                <View style={[styles.labelItemBox, { backgroundColor: this.state.isJoin ? '#FFF7E0' : '#F4F4F4' }]}>
                                    <Text style={[styles.labelText, { color: this.state.isJoin ? '#FF7B00' : '#666' }]}>{this.state.isJoin ? '已上架' : '未上架'}</Text>
                                </View>

                                {/* 已预订 */}
                                {
                                    this.state.data.saleStatus == 3 ?
                                        <View style={[styles.labelItemBox, { backgroundColor: '#FFF7E0' }]}>
                                            <Text style={[styles.labelText, { color: '#FF7B00' }]}>已预订</Text>
                                        </View>
                                        :
                                        null
                                }

                                {/* 检测状态 */}
                                {
                                    this.state.data.detectionStatus ?
                                        <View style={[styles.labelItemBox, { backgroundColor: this.state.data.detectionStatus == 3 ? '#FFF7E0' : '#F4F4F4' }]}>
                                            <Text style={[styles.labelText, { color: this.state.data.detectionStatus == 3 ? '#FF7B00' : '#666' }]}>{conditionObjWithType('carDetectionStatus')[this.state.data.detectionStatus]}</Text>
                                        </View>
                                        :
                                        <View style={styles.labelItemBox}>
                                            <Text style={styles.labelText}>{'未自检'}</Text>
                                        </View>
                                }
                            </View>
                        </View>

                        {
                            this.state.isFranchisee ?
                                <PublishCarTextInput
                                    name={'采购价'}
                                    value={this.state.purchasePrice}
                                    unit={'万元'}
                                    keyboardType={'decimal-pad'}
                                    onChangeText={(value) => {
                                        this.setState({
                                            purchasePrice: value
                                        })
                                    }}
                                />: null
                        }


                        <PublishCarTextInput
                            name={this.state.isFranchisee ? '展厅价' : '一口价'}
                            value={this.state.markedPrice}
                            unit={'万元'}
                            keyboardType={'decimal-pad'}
                            onChangeText={(value) => {
                                this.setState({
                                    markedPrice: value
                                })
                            }}
                        />

                        {
                            this.state.isFranchisee ?
                                <PublishCarTextInput
                                    name={'挂牌价'}
                                    value={this.state.listPrice}
                                    unit={'万元'}
                                    keyboardType={'decimal-pad'}
                                    onChangeText={(value) => {
                                        this.setState({
                                            listPrice: value
                                        })
                                    }}
                                />
                                :
                                <PublishCarTextInput
                                    name={'批发价'}
                                    value={this.state.wholesalePrice}
                                    unit={'万元'}
                                    keyboardType={'decimal-pad'}
                                    onChangeText={(value) => {
                                        this.setState({
                                            wholesalePrice: value
                                        })
                                    }}
                                />
                        }

                        {
                            this.state.isFranchisee ?
                                <PublishCarSwitch
                                    name={'上架到报价中心'}
                                    hideSepline={true}
                                    value={this.state.joinQuotationCenter}
                                    valueChanged={(value) => {
                                        this.setState({
                                            joinQuotationCenter: value
                                        })
                                    }}
                                />
                                :
                                <PublishCarSwitch
                                    name={'上架到严选车源'}
                                    hideSepline={true}
                                    value={this.state.joinUnion}
                                    valueChanged={(value) => {
                                        this.setState({
                                            joinUnion: value
                                        })
                                    }}
                                />
                        }

                    </View>

                </ScrollView>

                <View style={[styles.bottomBox, { height: 60 + Constant.bottomHeight }]}>
                    <TouchableOpacity
                        style={styles.submitBox}
                        activeOpacity={0.8}
                        onPress={() => {
                            this.submit()
                        }}
                    >
                        <Text style={styles.submitText}>提交</Text>
                    </TouchableOpacity>
                </View>

                <Loading onRef={(ref) => (this.Loading = ref)} />

                <DatePickerPart type={this.state.dateTypeMode} defaultDate={this.state[this.state.tradeDate]} show={this.state.showDatePicker} changeState={
                    (val) => { // 时间选择组件显示与否
                        this.setState({
                            showDatePicker: val,
                        })
                    }
                } changeDate={(date) => {
                    this.setState({
                        tradeDate: date,
                    })
                }} />

            </View>
        )
    }

    getDaysBetweenDates(dateString) {
        let pastDate = new Date(dateString);
        let currDate = new Date()
        const timeDiff = Math.abs(currDate.getTime() - pastDate.getTime());
        // 将毫秒转换为天数
        return Math.floor(timeDiff / (1000 * 60 * 60 * 24)) + 1;
    }

    //输入框内容输入
    changeText(type, val) {
        this.setState({
            [type]: val
        })
    }

    submit() {
        // if (this.state.markedPrice == '') {
        //     ToastToUser('请填写展厅价')
        //     return
        // }
        // if (this.state.listPrice == '') {
        //     ToastToUser('请填写挂牌价')
        //     return
        // }

        let params = {
            carId: this.state.carId,
            merchantId: Constant.userInfo.merchantId,
            userId: Constant.userInfo.userId,
        }

        if (this.state.purchasePrice) {
            params['purchasePrice'] = this.state.purchasePrice * 10000
        }
        if (this.state.markedPrice) {
            params['markedPrice'] = this.state.markedPrice * 10000
        }

        if (this.state.listPrice) {
            params['listPrice'] = this.state.listPrice * 10000
        }

        if (this.state.wholesalePrice) {
            params['wholesalePrice'] = this.state.wholesalePrice * 10000
        }

        if (this.state.isFranchisee) {
            params['joinQuotationCenter'] = this.state.joinQuotationCenter ? 1 : 0
        } else {
            params['joinUnion'] = this.state.joinUnion ? 1 : 0
        }

        if (this.Loading) {
            this.Loading.show('提交中...');
        }
        HttpUtils.postRequest(HttpUrls.setCarPrices, params)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {
                    ToastToUser('提交成功!')
                    if (this.props.route.params && this.props.route.params.completion) {
                        setTimeout(() => {
                            this.props.route.params.completion()
                        }, 500);
                    }
                } else {
                    ToastToUser(result.msg ? result.msg : result.statusText)
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });

    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },
    sepLine: {
        width: '100%',
        height: 10
    },
    contentContainer: {
        width: '100%',
        flexDirection: 'column',
        backgroundColor: '#fff',
        paddingHorizontal: 16,

    },
    carInfoBox: {
        width: '100%',
        paddingVertical: 12,
        flexDirection: 'column',

    },
    carBox: {
        flexDirection: 'row',

    },
    carImg: {
        width: 130,
        height: 90,
        borderRadius: 4,
        backgroundColor: '#f9f9f9'
    },
    carRightBox: {
        height: 90,
        flex: 1,
        marginLeft: 12,
        flexDirection: 'column',
        justifyContent: 'flex-start',
        alignItems: 'flex-start'
    },
    brandText: {
        marginTop: 5,
        color: '#333',
        fontSize: 14,
    },
    dateText: {
        marginTop: 5,
        color: '#666',
        fontSize: 14,
    },
    priceText: {
        marginTop: 24,
        color: '#FD6521',
        fontSize: 16,
        fontWeight: '500',
        lineHeight: 20,
    },
    markBox: {
        marginTop: 8,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start',
    },
    labelItemBox: {
        marginRight: 6,
        paddingHorizontal: 10,
        height: 21,
        flexDirection: 'row',
        alignItems: 'center',
        borderRadius: 2,
        backgroundColor: '#F4F4F4'
    },
    labelText: {
        fontSize: 12,
        color: '#666'
    },


    bottomBox: {
        backgroundColor: '#fff',
        width: '100%',
        paddingTop: 7,
        paddingHorizontal: 15,
        flexDirection: 'column',
        alignItems: 'center'
    },
    submitBox: {
        width: '100%',
        height: 46,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#FFE000',
        borderRadius: 23
    },
    submitText: {
        color: '#333333',
        fontSize: 16
    }

})